package jjn.carl.linkedlist;

/**
 * @author Jiang Jining
 * @since 2023-06-30 22:45
 */
public class LeetCode707 {
    
    class Node {
        int val;
        Node next;
        
        public Node(int val) {
            this.val = val;
        }
    }
    
    private final Node dummy;
    private int size;
    
    public LeetCode707() {
        dummy = new Node(0);
        size = 0;
    }
    
    public int get(int index) {
        Node start = dummy;
        if (index < 0 || index > size - 1) {
            return -1;
        }
        while (index >= 0) {
            start = start.next;
            index--;
        }
        return start.val;
    }
    
    public void addAtHead(int val) {
        addAtIndex(0, val);
    }
    
    public void addAtTail(int val) {
        addAtIndex(size, val);
    }
    
    public void addAtIndex(int index, int val) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("index out of bound...");
        }
        Node start = dummy;
        while (index > 0) {
            start = start.next;
            index--;
        }
        Node next = new Node(val);
        next.next = start.next;
        start.next = next;
        size++;
    }
    
    public void deleteAtIndex(int index) {
        if (index >= size) {
            return;
        }
        Node start = dummy;
        while (index > 0) {
            start = start.next;
            index--;
        }
        start.next = start.next.next;
        size--;
    }
    
    public static void main(String[] args) {
        LeetCode707 leetCode707 = new LeetCode707();
        leetCode707.addAtHead(7);
        leetCode707.addAtHead(2);
        leetCode707.addAtHead(1);
        leetCode707.addAtIndex(3, 0);
        leetCode707.deleteAtIndex(2);
        leetCode707.addAtHead(6);
        leetCode707.get(4);
        System.out.println("leetCode707.get(4) = " + leetCode707.get(4));
        leetCode707.addAtHead(4);
        leetCode707.addAtIndex(5, 0);
        leetCode707.addAtHead(6);
    }
}
